package fr.mma.livraison.channel;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.channel.ChannelPresence;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

import fr.mma.livraison.channel.dao.ChannelDao;
import fr.mma.livraison.channel.dto.Message;
import fr.mma.livraison.channel.persistance.Channel;

public class DisconnectedServlet extends MessageEnabledServlet{

	/**	 */
	private static final long serialVersionUID = -7480624595793659454L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		ChannelPresence presence = channelService.parsePresence(req);
		final ChannelDao dao = new ChannelDao();
		for (Channel channel : dao.getAll()) {
			if(channel.getChannelKeyList() != null && channel.getChannelKeyList().contains(presence.clientId())) {
				channel.getChannelKeyList().remove(presence.clientId());
				Message message = new Message();
				message.setType("DISCONNECTED");
				message.setData(String.valueOf(channel.getChannelKeyList().size()));
				sendMessage(channel, message);
				dao.save(channel);
			}
		} 

	}
}
